import axios from 'axios'
import Config from './../http/Config'
export default class File {
  _dealFileType (file) {
    return new Promise((resolve, reject) => {
      let imgExt = ["png", "jpg", "jpeg", "bmp", "gif"];//图片文件的后缀名
      let docExt = ["doc", "docx", "xls", "xlsx"];//word excel文件的后缀名
      let imgObj = {
        imgUrl: '',
        type: ''
      };
      let arr = file.name.split(".");
      let type = arr[arr.length - 1];
      imgObj.type = type;
      if (imgExt.indexOf(type) > -1) {
        // 如果是图片要进行处理
        this.getPictureBase64(file, (data) => {
          imgObj.url = data;
          resolve(imgObj)
        })
      }
      if (docExt.indexOf(type) > -1) {
        let name = file.name;
        let size = parseInt(file.size / 1024);
        let obj = {
          name: name,
          size: size,
          type: type
        };
        resolve(obj);
      }
    })
  }
  getPictureBase64 (file, callback) {
    let reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function (e) {
      if (callback) {
        callback(e.target.result)
      }
    }
  }
  dealPasteData(clipboardData){
    return new Promise((resolve, reject)=>{
      let items, item, types;
      if( clipboardData ){
        items = clipboardData.items;
        if( !items ){
          return;
        }
        item = items[0];
        // 保存在剪贴板中的数据类型
        types = clipboardData.types || [];
        console.log(types)
        for(let  i = 0; i < types.length; i++ ){
          if( types[i] === 'Files' ){
            item = items[i];
            break;
          }else{
            item.getAsString(function (str) {
              let obj = {
                type:'str',
                str:str
              };
              resolve(obj)
            })
          }
        }
        // 判断是否为图片数据
        if( item && item.kind === 'file' && item.type.match(/^image\//i) ){

          this.imgReader(item,resolve);
        }
      }
    })
  }
  imgReader(item,resolve){
    let blob = item.getAsFile();
        console.log(blob);
     let   reader = new FileReader();
    // 读取文件后将其显示在网页中
    reader.onload = function (e) {
      let picObj = {
          url:e.target.result,
          file:blob,
          type:'file'
      };
      resolve(picObj)
    };
    // 读取文件
    reader.readAsDataURL(blob)
  }
  uploadFile(file,type){
    return new Promise((resolve,reject)=>{
      let param = new FormData();
      param.append('filedata', file);
      axios({
        method: 'POST',
        url: '/im/sendFile',
        data: param,
        baseURL: Config.chatUrl,
        withCredentials: false,
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(function(res) {
          if(res.data.code == 200){
            resolve(res.data.data[0])
          }
      })
    })
  }

}